package com.cxx.initializer;

import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 自定义ServletContainerInitializer
 * 通过该方法调用自定义的MyWebApplicationInitializer
 */
@HandlesTypes(CxxWebApplicationInitializer.class)
public class MySpringServletContainerInitializer implements ServletContainerInitializer {

    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        System.out.println("MySpringServletContainerInitializer start gogogo");
        List<CxxWebApplicationInitializer> initializers = new ArrayList<>();
        if (set != null) {
            // 遍历类集合
            for (Class<?> clazz : set) {
                // 判断如果该类不是接口，不是抽象类，并且是WebApplicationInitializer类型的类，则实例化放到list中
                if (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()) &&
                        CxxWebApplicationInitializer.class.isAssignableFrom(clazz)) {
                    try {
                        initializers.add((CxxWebApplicationInitializer) clazz.getDeclaredConstructor().newInstance());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        if (initializers.isEmpty()) {
            servletContext.log("没有获取到WebApplicationInitializer的实例");
            return;
        }

        // 循环list集合，执行onStartup方法
        for (CxxWebApplicationInitializer initializer : initializers) {
            initializer.onStartup(servletContext);
        }
    }
}
